import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { DownOutlined, PlusOutlined, UpOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Row,
  Col,
  Card,
  Input,
  Button,
  Dropdown,
  Menu,
  Modal,
  message,
  Badge,
  Divider,
  Tooltip,
} from 'antd';
import router from 'umi/router';
import Link from 'umi/link';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { checkPermissions } from '@/utils/authority';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
import Area from '../../components/Area';
import NsCustomer from '../../components/NsCustomer';
import Supplier from '../../components/NsSupplier';
import TextOverFlow from '../../components/TextOverFlow';
import AddEditModal from './AddEditModal';

const FormItem = Form.Item;

@connect(({ protocol, loading }) => ({
  data: protocol.data,
  dataInfo: protocol.detail || {},
  productList: protocol.addOrEdit.productList,
  loading: loading.effects['protocol/fetchList'],
  areaLoading: loading.effects['protocol/fetchAreaList'],
  confirmLoading: loading.effects['protocol/addList'] || loading.effects['protocol/updateList'],
  formFieldsValue: protocol.formFieldsValue,
  expandForm: protocol.expandForm,
  modalData: protocol.modalData,
  valuesArr: protocol.valuesArr,
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      formValues: {},
      modalVisible: false,
      selectedRows: [],
      selectedRowKeys: [],
      suppId: '',
      areaList: [],
    };

    this.tableSearchLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };

    this.columns = [
      {
        title: '协议名称',
        dataIndex: 'suppProtName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '供应商',
        dataIndex: 'recvSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '执行地区',
        dataIndex: 'areaNameList',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '服务产品',
        dataIndex: 'pdNameList',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        // eslint-disable-next-line no-unused-vars
        render: (val, record) => (
          <Tooltip
            title={
              record &&
              record.packList.map(ites => (
                <div>
                  <span>{ites.pdNameList}</span>
                  <span style={{ margin: '0 0 0 5px' }}>{ites.detList[0].fee}</span>
                  <br />
                </div>
              ))
            }
            // eslint-disable-next-line no-undef
          >
            <div
              style={{
                width: '160px',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                cursor: 'pointer',
              }}
            >
              {val}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '价格',
        dataIndex: 'money',
        // sorter: (a, b) => parseInt(b.price, 10) - parseInt(a.price, 10),
        sorter: (a, b) => b.money - a.money,
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        align: 'right',
        needTotal: true,
      },
      {
        title: '状态',
        dataIndex: 'validFlag',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render(val) {
          return (
            <Badge status={val === 1 ? 'success' : 'error'} text={val === 1 ? '有效' : '已废弃'} />
          );
        },
      },
      {
        title: '操作',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) =>
          record.validFlag === 1 ? (
            <Fragment>
              <Link to={`/supplymanage/protocol/detail?suppProtId=${record.suppProtId}`}>查看</Link>
              <Divider type="vertical" />
              <Dropdown
                overlay={
                  <Menu>
                    {checkPermissions('business:suppProto:update') && (
                      <Menu.Item key="update" onClick={() => this.update(record.suppProtId)}>
                        修改
                      </Menu.Item>
                    )}
                    <Menu.Item
                      key="updateStatus"
                      onClick={() => this.updateStatus(record.suppProtId)}
                    >
                      作废
                    </Menu.Item>
                  </Menu>
                }
              >
                <a>
                  更多 <DownOutlined />
                </a>
              </Dropdown>
            </Fragment>
          ) : (
            <Link to={`/supplymanage/protocol/detail?suppProtId=${record.suppProtId}`}>查看</Link>
          ),
      },
    ];
  }

  componentDidMount() {
    this.getInitialList();
  }

  getInitialList = () => {
    const {
      data: { pagination },
      dispatch,
      location,
      formFieldsValue,
    } = this.props;
    if (location.queryParam) {
      if (location.queryParam && location.queryParam.suppId) {
        location.queryParam.recvSuppId = location.queryParam.suppId;
      }
      dispatch({
        type: 'protocol/updateModelData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = () => {
    const { form, valuesArr, dispatch } = this.props;
    form.validateFieldsAndScroll([...valuesArr], (err, values) => {
      if (!err) {
        dispatch({
          type: 'protocol/updateModelData',
          payload: {
            formFieldsValue: values,
          },
        });
        this.searchList(this.processFormData(values));
      }
    });
  };

  // 查询
  searchList = (formFieldsValue, currentPage = 1, pageSize = 10, isClear = true) => {
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }

    const { dispatch } = this.props;
    const pagerArg = { currentPage, pageSize };
    const values = {
      ...formFieldsValue,
      pagerArg,
    };

    dispatch({
      type: 'protocol/updateModelData',
      payload: {
        values,
      },
    });

    dispatch({
      type: 'protocol/fetchList',
      payload: values,
    });
    this.setState({
      formValues: values,
    });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'suppProtName') {
        tempFieldsValue[key] = (tempFieldsValue[key] && tempFieldsValue[key].trim()) || null;
      }
      formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
    });
    return formFieldsValue;
  };

  // 重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'protocol/updateModelData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
  };

  // 切换表格展开收起
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'protocol/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const getValue = obj =>
      Object.keys(obj)
        .map(key => obj[key])
        .join(',');
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const pagerArg = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    };
    const params = {
      ...formValues,
      ...filters,
      pagerArg,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    dispatch({
      type: 'protocol/fetchList',
      payload: params,
    });
  };

  // 更改状态:废弃
  updateStatus = suppProtId => {
    const { dispatch, formFieldsValue } = this.props;
    Modal.confirm({
      title: `你确定要废弃此协议吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'protocol/updateStatus',
          payload: { suppProtId },
          callback: response => {
            if (response.success) {
              this.searchList(this.processFormData(formFieldsValue));
              message.success('废弃成功！');
            } else {
              message.warning('废弃失败!');
            }
          },
        });
      },
    });
  };

  // 模态框显隐
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  // 获取当前供应商下地区列表
  getAreaList = suppId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'protocol/fetchAreaList',
      payload: { suppId },
    }).then(response => {
      if (response && response.success && response.data && response.data.length) {
        this.setState({ areaList: response.data });
      } else {
        this.setState({ areaList: [] });
        message.warning((response && response.message) || '该供应商业务范围下未维护地区！');
      }
    });
  };

  // 获取供应商名称
  getSuppName = value => {
    this.getAreaList(value);
    this.setState({ suppId: value });
  };

  // 选择地区
  selectArea = value => {
    const { suppId } = this.state;
    if (suppId) {
      this.getProductList(suppId, value);
    }
  };

  // 获取产品下拉数据
  getProductList = (suppId, areaIdList) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'protocol/fetchProductList',
      payload: { suppId, areaIdList },
    });
  };

  // 添加
  add = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'protocol/getDetail',
      payload: {},
    });
    this.handleModalVisible(true);
  };

  // 修改
  update = suppProtId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'protocol/fetchDetail',
      payload: { suppProtId },
      callback: response => {
        const areaIdList = [];
        response.areaList.forEach(item => {
          areaIdList.push(item.areaId);
        });
        this.setState({ suppId: response.recvSuppId });
        this.getProductList(response.recvSuppId, areaIdList);
        if (response.custId) {
          dispatch({
            type: 'publicdata/getNsCustList',
            payload: [{ mdCustId: response.custId, name: response.custName }],
          });
          dispatch({
            type: 'publicdata/updateModelData',
            payload: { custNsFsValue: { title: response.custName } },
          });
        }
        dispatch({
          type: 'publicdata/updateModelData',
          payload: { nsSupplyFsValue: { title: response.recvSuppName } },
        });
        this.getAreaList(response.recvSuppId);
        this.handleModalVisible(true);
      },
    });
  };

  // 提交数据
  submitData = values => {
    const { dispatch, dataInfo, formFieldsValue } = this.props;
    if (dataInfo.suppProtId) {
      // 修改
      dispatch({
        type: 'protocol/updateList',
        payload: { ...values, suppProtId: dataInfo.suppProtId },
        callback: response => {
          if (response.success) {
            this.searchList(this.processFormData(formFieldsValue));
            message.success('修改成功！');
            this.handleModalVisible();
          } else {
            message.warning(`${response.message || '修改失败！'}`);
          }
        },
      });
    } else {
      // 新增
      dispatch({
        type: 'protocol/addList',
        payload: values,
        callback: response => {
          if (response.success) {
            this.searchList(this.processFormData(formFieldsValue));
            message.success('添加成功！');
            this.handleModalVisible();
          } else {
            message.warning(`${response.message || '添加失败！'}`);
          }
        },
      });
    }
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="协议名称" {...this.tableSearchLayout}>
              {getFieldDecorator('suppProtName', {
                initialValue: formFieldsValue.suppProtName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="供应商" {...this.tableSearchLayout}>
              {getFieldDecorator('recvSuppId', {
                initialValue: formFieldsValue.recvSuppId,
              })(<Supplier allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={this.searchBtnList}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="协议名称" {...this.tableSearchLayout}>
              {getFieldDecorator('suppProtName', {
                initialValue: formFieldsValue.suppProtName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="供应商" {...this.tableSearchLayout}>
              {getFieldDecorator('recvSuppId', {
                initialValue: formFieldsValue.recvSuppId,
              })(<Supplier allowClear params={{ status: 2 }} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="客户名称" {...this.tableSearchLayout}>
              {getFieldDecorator('custId', {
                initialValue: formFieldsValue.custId,
              })(<NsCustomer allowClear />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="执行地区" {...this.tableSearchLayout}>
              {getFieldDecorator('areaId', {
                initialValue: formFieldsValue.areaId,
              })(<Area allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <div style={{ float: 'right', marginBottom: 16 }}>
                <Button type="primary" onClick={this.searchBtnList}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起
                  <UpOutlined />
                </a>
              </div>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const {
      data,
      loading,
      productList,
      dataInfo,
      areaLoading,
      confirmLoading,
      modalData,
    } = this.props;
    const { selectedRows, selectedRowKeys, modalVisible, areaList } = this.state;
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card className={styles.tableCard}>
          <div className={styles.tableList}>
            <div className={styles.tableListOperator}>
              <Authorized authority="ns:supply:protocol" noMatch={null}>
                <Button icon={<PlusOutlined />} type="primary" onClick={this.add}>
                  添加
                </Button>
              </Authorized>
              <Authorized authority="business:suppProto:uploadSuppProt" noMatch={null}>
                <Button onClick={() => router.push(`/supplymanage/protocol/batchadd`)}>
                  批量新增
                </Button>
              </Authorized>
            </div>
            <StandardTable
              selectedRows={selectedRows}
              selectedRowKeys={selectedRowKeys}
              loading={loading}
              data={data}
              rowKey="suppProtId"
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
          <AddEditModal
            modalVisible={modalVisible}
            handleModalVisible={this.handleModalVisible}
            getSuppName={this.getSuppName}
            selectArea={this.selectArea}
            areaList={areaList}
            productList={productList}
            dataInfo={dataInfo}
            submitData={this.submitData}
            areaLoading={areaLoading}
            confirmLoading={confirmLoading}
            modalData={modalData}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default TableList;
